Integrating and Developing with CookieBanner
Introduction
This guide explains how to integrate the CookieBanner's accept/decline mechanism into your own Paymenter extension. The CookieBanner extension sets a cookie (cookieConsent) when a user accepts or declines cookies. You can use this cookie to conditionally execute code in your extension based on the user's consent.
Prerequisites
- A working Paymenter instance.
- The CookieBanner extension installed and enabled.
- Basic knowledge of PHP and JavaScript.
Integration Steps
1. Create a New Extension
Start by creating a new extension in your Paymenter instance. Use the following template as a starting point:
<?php
namespace Paymenter\Extensions\Others\Example;
use App\Classes\Extension\Extension;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\HtmlString;
class Example extends Extension
{
public function boot(): void
{
if (!request()->isMethod('GET')) {
return;
}
Event::listen('body', function () {
return ['view' => new HtmlString($this->getScriptTemplate())];
});
}
private function getScriptTemplate(): string
{
return <<
document.addEventListener("DOMContentLoaded", function() {
const cookieConsent = document.cookie.includes("cookieConsent=accepted")
? "accepted"
: document.cookie.includes("cookieConsent=declined")
? "declined"
: null;
if (cookieConsent === "accepted") {
// Code to run when cookies are accepted
console.log("Accepted: place your code here.");
}
if (cookieConsent === "declined") {
// Code to run when cookies are declined
console.log("Declined: place your code here.");
}
});
HTML;
}
public function enabled(): void {}
public function disabled(): void {}
public function updated(): void {}
public function install(): void {}
}
Understanding the Cookie Consent Check
How the Cookie Check Works
The JavaScript code checks for the presence of the cookieConsent cookie to determine the user's consent status. Here's how it works:
- The script first checks if the
cookieConsentcookie is set to"accepted".
- If the cookie is not set to
"accepted", the script then checks if it is set to"declined".
- If neither
"accepted"nor"declined"is found in the cookie, thecookieConsentvariable is set tonull, indicating that the user has not yet made a choice.
Using the Consent Status
Once the cookieConsent status is determined, you can use it to control the behavior of your website:
- If
cookieConsentis"accepted":
- If
cookieConsentis"declined":
- If
cookieConsentisnull:
Practical Applications
- Analytics and Tracking:
- Personalized Content:
- Third-Party Integrations:
- User Experience:
Best Practices
- Transparency:
- Respect User Choice:
- Testing:
- Fallbacks: